<template>
  <div class="video-player">
    <video
      ref="videoRef"
      class="video-element"
      controls
      :src="videoSource"
      controlsList="nodownload"
      preload="auto"
      @error="handleVideoError"
      crossorigin="anonymous"
    >
      <source :src="videoSource" type="video/mp4">
      您的浏览器不支持视频播放。
    </video>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  video: {
    type: [String, File],
    required: true
  }
})

const videoRef = ref(null)
const objectUrl = ref(null)

// 添加视频源处理
const videoSource = computed(() => {
  if (typeof props.video === 'string') {
    // 处理URL中的特殊字符
    return decodeURIComponent(props.video)
      .replace(/\|/g, '%7C')
      .replace(/\s/g, '%20')
  }
  return objectUrl.value
})

// 改进错误处理
const handleVideoError = (e) => {
  console.error('视频加载错误:', {
    error: e,
    errorCode: e.target.error?.code,
    errorMessage: e.target.error?.message,
    videoSrc: videoSource.value
  })
  
  // 显示友好的错误提示
  ElMessage.error('视频加载失败，请稍后重试')
}

// 添加视频加载事件监听
onMounted(() => {
  if (videoRef.value) {
    videoRef.value.addEventListener('loadedmetadata', () => {
      console.log('视频元数据加载成功')
    })
    
    videoRef.value.addEventListener('canplay', () => {
      console.log('视频可以开始播放')
    })
  }
})

watch(() => props.video, (newValue) => {
  if (objectUrl.value) {
    URL.revokeObjectURL(objectUrl.value)
    objectUrl.value = null
  }

  if (newValue instanceof File) {
    objectUrl.value = URL.createObjectURL(newValue)
  }
  
  // 重置视频元素
  if (videoRef.value) {
    videoRef.value.load()
  }
}, { immediate: true })

onBeforeUnmount(() => {
  if (objectUrl.value) {
    URL.revokeObjectURL(objectUrl.value)
    objectUrl.value = null
  }
})
</script>

<style scoped>
.video-player {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;
}

/* 添加加载状态样式 */
.video-element:not([src]) {
  opacity: 0.5;
}
</style> 